package com.renrenyou.duanshipin.material;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.ExoPlayer;

import com.bumptech.glide.Glide;
import com.renrenyou.duanshipin.R;
import com.renrenyou.duanshipin.base.BaseActivity;
import com.renrenyou.duanshipin.databinding.ActivityMaterialBinding;
import com.renrenyou.duanshipin.util.ClipboardUtils;
import com.renrenyou.duanshipin.util.DownloadFileUtil;
import com.renrenyou.duanshipin.util.StoragePermissionHelper;
import com.renrenyou.duanshipin.util.ToastUtil;

import okhttp3.Call;

public class MaterialActivity extends BaseActivity<ActivityMaterialBinding> implements View.OnClickListener {

    private Call mFileCall;
    private ExoPlayer mPlayer;
    private String mDesc;
    private String mVideoUrl;

    @Override
    public ActivityMaterialBinding getBinding(LayoutInflater inflater) {
        return ActivityMaterialBinding.inflate(inflater);
    }

    public static void startThisActivity(Context context, String title, String videoPath) {
        Intent intent = new Intent(context, MaterialActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("videoPath", videoPath);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        Glide.with(this).load(R.mipmap.ic_material_bg).into(mBinding.ivMaterialBg);
        mBinding.tvMaterialTiqu.setOnClickListener(this);
        mBinding.tvMaterialSave.setOnClickListener(this);

        if (getIntent() != null) {
            mDesc = getIntent().getStringExtra("title");
            mBinding.materialContent.setText(mDesc);
            playVideo(getIntent().getStringExtra("videoPath"));
        }
    }

    private void playVideo(String url) {
        if (TextUtils.isEmpty(url)) {
            Log.d("materialActivity", "url is empty!");
            ToastUtil.showToast(this, "视频地址无效!");
            return;
        }
        mVideoUrl = url;
        mPlayer = new ExoPlayer.Builder(this).build();
        mBinding.ivMaterialContent.setPlayer(mPlayer);
        MediaItem mediaItem = MediaItem.fromUri(url);
        mPlayer.setMediaItem(mediaItem);
        mPlayer.prepare();
        mPlayer.play();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_material_tiqu) {
            if (TextUtils.isEmpty(mDesc)) {
                return;
            }
            ClipboardUtils.copyToClipboard(this, mDesc);
        } else if (view.getId() == R.id.tv_material_save) {
            if (TextUtils.isEmpty(mVideoUrl)) {
                return;
            }
            if (!StoragePermissionHelper.hasStoragePermission(this)) {
                StoragePermissionHelper.requestStoragePermission(this);
            } else {
                // 已经有权限，执行文件操作
                performFileOperations();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StoragePermissionHelper.handlePermissionResult(this, requestCode, grantResults);

        if (requestCode == StoragePermissionHelper.STORAGE_PERMISSION_REQUEST_CODE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            performFileOperations();
        }
    }

    private void performFileOperations() {
        mBinding.upvProgress.setVisibility(View.VISIBLE);
        mFileCall = DownloadFileUtil.downloadFile(this, mVideoUrl, mBinding.upvProgress);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer != null) {
            mPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        if (mPlayer != null) {
            mPlayer.release();
        }
        if (mFileCall != null) {
            mFileCall.cancel();
        }
        super.onDestroy();
    }
}
